#!/bin/bash
# TODO: test again, don't think this is currently working

# Ensure jq is installed
if [[ ! -x "$(which jq)" ]]; then
  echo "jq (a tool for parsing json in the command line) is required..."
  echo "https://stedolan.github.io/jq/download/"
  exit 1
fi

# Ensure docker is installed
if [[ ! -x "$(which docker-compose)" ]]; then
  echo "docker (a containerization tool) is required..."
  echo "https://docs.docker.com/compose/install/"
  exit 1
fi

RELAYER_DIR="$GOPATH/src/github.com/cosmos/relayer"
RELAYER_CONF="$HOME/.relayer"
ENV_FILE="$RELAYER_DIR/.env"

# Ensure user understands what will be deleted
if [[ -d $RELAYER_CONF ]] && [[ ! "$1" == "skip" ]]; then
  read -p "$0 will delete ~/.relayer folder and \$(pwd)/.env file. Do you wish to continue? (y/n): " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
      exit 1
  fi
fi

echo "Stopping any existing containers..."
docker-compose down &> /dev/null

cd $RELAYER_DIR
rm -rf $RELAYER_CONF &> /dev/null
rm -rf $ENV_FILE &> /dev/null
touch $ENV_FILE

make install

echo "Generating rly configurations..."
rly cfg i

echo "Adding configuration..."
rly cfg ad configs/four/ &> /dev/null

echo "Generating keys..."
echo "IBC0ADDR=$(rly k a ibc-0 | jq -r '.address')" >> $ENV_FILE
echo "IBC1ADDR=$(rly k a ibc-1 | jq -r '.address')" >> $ENV_FILE
echo "IBC2ADDR=$(rly k a ibc-2 | jq -r '.address')" >> $ENV_FILE
echo "IBC3ADDR=$(rly k a ibc-3 | jq -r '.address')" >> $ENV_FILE

echo "Creating containers..."
docker-compose up -d &> /dev/null

echo "Waiting for blocks..."
sleep 8

echo "Creating light clients for chains..."
rly light init ibc-0 -f
rly light init ibc-1 -f
rly light init ibc-2 -f
rly light init ibc-3 -f

echo "Starting 'rly tx link zeroone' (ibc-0<>ibc-1) logs in data/zeroone.log"
rly tx link zeroone -d -o 3s 2>&1 > data/zeroone.log &
sleep 1
echo "Starting 'rly tx link twothree' (ibc-2<>ibc-3) logs in data/twothree.log"
rly tx link twothree -d -o 3s 2>&1 > data/twothree.log &
sleep 1
echo "Starting 'rly tx link onetwo' (ibc-1<>ibc-2) logs in data/onetwo.log"
rly tx link onetwo -d -o 3s 2>&1 > data/onetwo.log &
sleep 2
echo "Starting 'rly tx link threezero' (ibc-3<>ibc-0) logs in data/threezero.log"
rly tx link threezero -d -o 3s 2>&1 > data/threezero.log &
sleep 1
echo "Check the state of the connections using 'rly paths list' to see when they are ready to relay over..."
rly paths list